package reqlog

import (
	"context"
	"fmt"
	"gitee.com/guolianyu/kit/str"
	"github.com/go-kratos/kratos/v2/middleware"
	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/trace"
)

type otions struct {
	debug bool
}
type Option func(*otions)

func Server(opts ...Option) middleware.Middleware {
	o := &otions{
		debug: false,
	}
	for _, v := range opts {
		v(o)
	}
	return func(handler middleware.Handler) middleware.Handler {
		return func(ctx context.Context, req interface{}) (res interface{}, err error) {
			res, err = handler(ctx, req)
			if !o.debug && err != nil { //TODO：只打印错误的请求
				trace.SpanFromContext(ctx).SetAttributes(
					attribute.String("param", str.ToJSON(req)),
					attribute.String("error", fmt.Sprint(err)),
					//attribute.String("response", str.ToJSON(res)), TODO：这里会导致es的数据量过大，暂时不打印
				)
			}
			return
		}
	}
}
